/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.U.
 */
package es.silenus.detecta.batch.processor;

import es.silenus.detecta.model.ImportedFile;
import es.silenus.detecta.model.SurveyAnswerHeaderImported;

import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;

import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemProcessor;

import java.sql.Date;


/**
 * Survey answer header processor.
 *
 * @author <a href="mailto:malonso@silenus-consultoria.es">Mariano Alonso</a>
 *
 * @since 24-ago-2009 18:17:49
 */
public class SurveyAnswerHeaderImportedProcessor implements ItemProcessor<SurveyAnswerHeaderImported, SurveyAnswerHeaderImported>,
	StepExecutionListener {
	/**
	 * The step execution.
	 */
	private StepExecution stepExecution;

	/**
	 * Process the provided item, returning a potentially modified or new item for continued processing.  If the
	 * returned result is null, it is assumed that processing of the item should not continue.
	 *
	 * @param item to be processed
	 *
	 * @return potentially modified or new item for continued processing, null if processing of the provided item should
	 * 				 not continue.
	 *
	 * @throws Exception
	 */
	public SurveyAnswerHeaderImported process(final SurveyAnswerHeaderImported item) throws Exception {
		if(item == null) {
			return null;
		}

		JobExecution jobExecution = stepExecution.getJobExecution();

		ExecutionContext context = jobExecution.getExecutionContext();

		item.setImportDate((Date)context.get("importDate"));
		item.setImportedFile((ImportedFile)context.get("importedFile"));

		return item;
	}

	/**
	 * Initialize the state of the listener with the {@link org.springframework.batch.core.StepExecution} from the
	 * current scope.
	 *
	 * @param stepExecution the step execution.
	 */
	public void beforeStep(final StepExecution stepExecution) {
		this.stepExecution = stepExecution;
	}

	/**
	 * Give a listener a chance to modify the exit status from a step. The value returned will be combined with the
	 * normal exit status using {@link
	 * org.springframework.batch.core.ExitStatus#and(org.springframework.batch.core.ExitStatus)}. Called after execution
	 * of step's processing logic (both successful or failed). Throwing exception in this method has no effect, it will
	 * only be logged.
	 *
	 * @param stepExecution the step execution.
	 *
	 * @return an {@link org.springframework.batch.core.ExitStatus} to combine with the normal value. Return null to
	 * 				 leave the old value unchanged.
	 */
	public ExitStatus afterStep(StepExecution stepExecution) {
		return null;
	}
}
